import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/home/index.dart';
import 'package:flutter_enjoy_plus/mine/index.dart';
import 'package:flutter_enjoy_plus/utils/Emitter.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({Key? key}) : super(key: key);

  @override
  _TabsPageState createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  @override
  void initState() {
    super.initState();
    // 初始化token
    tokenManager.init();
  }

  registerLogoutEvent() {
    eventBus.on<LogoutEvent>().listen((event) {
      Navigator.pushNamed(context, '/login');
    });
  }

  final List _tabbarList = [
    {
      'lable': '首页',
      'icon': 'assets/tabs/home_default.png',
      'activeIcon': 'assets/tabs/home_active.png'
    },
    {
      'lable': '我的',
      'icon': 'assets/tabs/my_default.png',
      'activeIcon': 'assets/tabs/my_active.png'
    }
  ];

//? 底部tabar 当前选中的index
  int _currentIndex = 0;

// //? 方案1：通过index来判断显示哪个页面
//   getTabbarContent() {
//     if (_currentIndex == 0) {
//       return const HomePage();
//     } else if (_currentIndex == 1) {
//       return const MinePage();
//     }
//   }

  List<BottomNavigationBarItem> getBottomNavigationBaritems() {
    List<BottomNavigationBarItem> list = [];
    for (var item in _tabbarList) {
      list.add(BottomNavigationBarItem(
          icon: Image.asset(item['icon'], width: 30, height: 30),
          label: item['lable'],
          activeIcon: Image.asset(item['activeIcon'], width: 30, height: 30)));
    }
    return list;
  }

  updateCurrentIndex(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //? safeArea : 顶部和底部安全区域，防止被遮挡
      // body: SafeArea(child: getTabbarContent()),
      body: IndexedStack(
        index: _currentIndex, //? 通过index来判断显示哪个页面
        children: [
          const HomePage(),
          MinePage(
              currentIndex: _currentIndex,
              updateCurrentIndex: updateCurrentIndex)
        ], //? 显示页面
      ),
      //? 底部tabBar T
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed, //? 底部tabBar类型
        currentIndex: _currentIndex, //? 当前选中的index
        items: getBottomNavigationBaritems(), //? 底部tabBar
        selectedItemColor: Colors.orange, //? 选中颜色
        unselectedItemColor: Colors.black, //? 未选中颜色
        onTap: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}
